package com.example.myblog_ssm.controller;

import com.example.myblog_ssm.common.AjaxResult;
import com.example.myblog_ssm.common.MarkdownToHtmlAndText;
import com.example.myblog_ssm.common.UserSessionUtils;
import com.example.myblog_ssm.entity.ArticleInfo;
import com.example.myblog_ssm.entity.UserInfo;
import com.example.myblog_ssm.service.ArticleService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 22479
 * Date: 2023-03-22
 * Time: 10:52
 */
@RestController
@RequestMapping("/art")
public class ArticleInfoController {

    @Resource
    private ArticleService articleService;

    /**
     * 获取用户文章列表
     *
     * @param request
     * @return
     */
    @RequestMapping("/mylist")
    public AjaxResult getMyList(HttpServletRequest request) {
        UserInfo userInfo = UserSessionUtils.getUserBySession(request);
        if (userInfo == null || userInfo.getId() < 0) {
            return AjaxResult.fail(-1, "非法请求");
        }
        //通过用户Id去查找对应作者发布过的文章
        List<ArticleInfo> list = articleService.getMyList(userInfo.getId());
        //返回给前端展示的时候,只返回给前150个字符
        for (ArticleInfo articleInfo : list) {
            articleInfo.setContent(MarkdownToHtmlAndText.MtoH(articleInfo.getContent()));

            if (articleInfo.getContent().length() >= 150) {
                articleInfo.setContent(articleInfo.getContent().substring(0, 151) + "······");
            }
        }

        return AjaxResult.success(list);
    }

    /**
     * 删除文章
     *
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("del")
    public AjaxResult del(Integer id, HttpServletRequest request) {
        //id是否有效
        if (id == null || id < 0) {
            return AjaxResult.fail(-1, "非法参数");
        }

        UserInfo userInfo = UserSessionUtils.getUserBySession(request);
        //用户是否登录
        if (userInfo == null) {
            return AjaxResult.fail(-2, "用户未登录");
        }
        return AjaxResult.success(articleService.del(id, userInfo.getId()));
    }

    /**
     * 通过ID查询文章详情
     *
     * @param id
     * @return
     */
    @RequestMapping("/detail")
    public AjaxResult getDetail(Integer id) {
        if (id == null || id < 0) {
            return AjaxResult.fail(-1, "非法参数");
        }
        ArticleInfo articleInfo = articleService.getDetail(id);
        if (articleInfo != null) {
            return AjaxResult.success(articleInfo);
        }
        return AjaxResult.fail(-1, "未查询到文章");
    }

    /**
     * 阅读量 每调用一次+1
     *
     * @param id
     * @return
     */
    @RequestMapping("/incr-rcoun")
    public AjaxResult incrRCount(Integer id) {
        //1.校验文章id是否正确
        if (id == null || id < 0) {
            return AjaxResult.fail(-1, "非法参数");
        }
        return AjaxResult.success(articleService.incrRCount(id));
    }

    /**
     * 发布文章功能 + 保存草稿功能
     *
     * @param articleInfo
     * @param request
     * @return
     */
    @RequestMapping("/add")
    public AjaxResult add(ArticleInfo articleInfo, HttpServletRequest request) {
        //1.非空校验
        if (articleInfo == null || !StringUtils.hasLength(articleInfo.getTitle()) || !StringUtils.hasLength(articleInfo.getContent())) {
            return AjaxResult.fail(-1, "非法参数");
        }
        //2.数据库添加操作
        //a.得到当前用户uid
        UserInfo userInfo = UserSessionUtils.getUserBySession(request);
        if (userInfo == null || userInfo.getId() < 0) {
            //无效用户登录
            return AjaxResult.success(-1, "无效用户登录");
        }
        //b.将UID给到articleInfo对象
        articleInfo.setUid(userInfo.getId());

        //d.添加数据库并返回结果
        int i = articleService.add(articleInfo);

        return AjaxResult.success(i);
    }

    /**
     * 修改发布过的文章
     *
     * @param articleInfo
     * @return
     */
    @RequestMapping("/update")
    public AjaxResult update(ArticleInfo articleInfo, HttpServletRequest request) {
        //1.非空校验
        if (articleInfo == null || !StringUtils.hasLength(articleInfo.getTitle()) || !StringUtils.hasLength(articleInfo.getContent())) {
            return AjaxResult.fail(-1, "非法参数");
        }
        //得到当前登录用户的id
        UserInfo userInfo = UserSessionUtils.getUserBySession(request);
        if (userInfo == null || userInfo.getId() < 0) {
            return AjaxResult.fail(-2, "无效用户");
        }
        //核心鉴权代码 || 重要!!!用于登录的用户 和 文章对应的发布作者是否是同一个
        articleInfo.setUid((userInfo.getId()));
        articleInfo.setUpdatetime(LocalDateTime.now());
        return AjaxResult.success(articleService.update(articleInfo));
    }

    /**
     * 查询列表根据分页
     *
     * @param pindex 当前页码（从1开始）
     * @param psize  每页显示条数
     * @return
     */
    @RequestMapping("/listbypage")
    public AjaxResult getListByPage(Integer pindex, Integer psize) {
        //1.参数校正
        if (pindex == null || pindex <= 1) {
            pindex = 1;
        }
        if (psize == null || psize <= 1) {
            psize = 4;
        }
        //分页公式 = (当前页码 - 1) * 每页显示条数
        int offset = (pindex - 1) * psize;
        //文章列表数据
        List<ArticleInfo> list = articleService.getListByPage(psize, offset);
        //返回给前端展示的时候,只返回给前150个字符
        for (ArticleInfo articleInfo : list) {
            articleInfo.setContent(MarkdownToHtmlAndText.MtoH(articleInfo.getContent()));
            if (articleInfo.getContent().length() >= 150) {
                articleInfo.setContent(articleInfo.getContent().substring(0, 151) + "······");
            }
        }
        //a.总共有多少条数据 --- 只计算已发布 state = 1
        int totalCount = articleService.getCount();
        //b.总条数 / psize = 总页数
        double pcountdb = (totalCount / (psize * 1.0));
        int pcount = (int) Math.ceil(pcountdb);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("list", list);
        hashMap.put("pcount", pcount);
        return AjaxResult.success(hashMap);

    }

    /**
     * 定时发布功能
     *
     * @param articleInfo 文章详情
     * @param publishTime 定时器
     * @param request
     * @return
     */
    @RequestMapping("/scheadd")
    public AjaxResult scheadd(ArticleInfo articleInfo, int publishTime, HttpServletRequest request) {
        //1.非空校验
        if (articleInfo == null || !StringUtils.hasLength(articleInfo.getTitle())
                || !StringUtils.hasLength(articleInfo.getContent())
                || publishTime <= 0) {
            System.out.println("test");
            return AjaxResult.fail(-1, "非法参数");
        }
        //2.获取UID
        //a.得到当前用户uid
        UserInfo userInfo = UserSessionUtils.getUserBySession(request);
        if (userInfo == null || userInfo.getId() < 0) {
            //无效用户登录
            return AjaxResult.success(-1, "无效用户登录");
        }
        //b.将UID给到articleInfo对象
        articleInfo.setUid(userInfo.getId());
        //3.定时器定时
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            //d.添加数据库并返回结果
            @Override
            public void run() {
                articleService.scheadd(articleInfo);
            }
        }, publishTime);
        return AjaxResult.success(1);
    }
}
